#!/bin/bash
#
# ifplugd daemon script for Arch Linux

. /etc/rc.conf
. /etc/rc.d/functions

shopt -s extglob

# env vars
daemonname=ifplugd
cfg=/etc/ifplugd/ifplugd.conf
PID=$(pidof -o %PPID ifplugd)

# source configuration file
[[ -r $cfg ]] && . "$cfg"

# discover interfaces to monitor
net_ifs=($INTERFACES)

case $1 in
  start)
    stat_busy "Starting $daemonname: ${net_ifs[*]}"

    for nic in "${net_ifs[@]}"; do
      # only start if a PID doesn't already exist
      if [[ ! -f /var/run/ifplugd.$nic.pid ]]; then
        /usr/bin/ifplugd-daemon $nic

        # use presence of PID file to check for start success
        [[ -f /var/run/ifplugd.$nic.pid ]] || (( ++err ))
      fi
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      add_daemon $daemonname
      stat_done
    fi
    ;;
  stop)
    stat_busy "Stopping $daemonname: ${net_ifs[*]}"

    for nic in /var/run/ifplugd.*.pid; do
      [[ -f $nic ]] || { (( ++err )); break; }
      nic=${nic%.pid}
      nic=${nic##*.}
      ifplugd -k -i "$nic" || (( ++err ))
    done

    if (( err )); then
      stat_fail
      exit 1
    else
      rm_daemon $daemonname
      stat_done
    fi
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  status)
    for nic in "${net_ifs[@]}"; do
      ifplugd -c -i "$nic"
    done
    unset nic
    ;;
  suspend)
    stat_busy "Suspending $daemonname: ${net_ifs[*]}"
    for nic in "${net_ifs[@]}"; do
      ifplugd -S -i $nic || (( ++err ))
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      stat_done
    fi
    ;;
  resume)
    stat_busy "Resuming $daemonname ${net_ifs[*]}"

    for nic in "${net_ifs[@]}"; do
      ifplugd -R -i $nic || (( ++err ))
    done
    unset nic

    if (( err )); then
      stat_fail
      exit 1
    else
      stat_done
    fi
    ;;
  *)
    echo "usage: $0 {start|stop|restart|status|suspend|resume}"
esac
exit 0
